class Admins::ViewArticlesController < Admins::BaseController

  before_action :set_seach_data,only: [:index]
  before_action :get_class,only: [:set_index,:up_index,:down_index,:del_index]

  def index
    article_type = params[:article_type] || session[:article_type]
    case article_type
      when '校园要闻'
        @dantengs = News.index_news.where(:is_important_news => 1).order("ordinal desc").order("created_at desc").page(params[:page])
      when '校园快讯'
        @dantengs = News.index_news.where(:is_important_news => 0).order("ordinal desc").order("created_at desc").page(params[:page])
      when '热点专题'
        @dantengs = Sptitle.all.order("ordinal desc").page(params[:page])
    end
  end


  #上移
  def up_index
    max_ordinal = @dandan_class.pluck(:ordinal).max
    dandan = @dandan_class.find params[:id]
    if (dandan.ordinal != max_ordinal) || (max_ordinal == 0)
      pre_dandan = @dandan_class.where(:ordinal => dandan.ordinal+1).first
      pre_ordinal = pre_dandan.blank? ? 1 : pre_dandan.ordinal
      pre_ordinal = max_ordinal +1 if dandan.ordinal == 0
      ordinal = dandan.ordinal
      dandan.update_attributes(:ordinal => pre_ordinal)
      pre_dandan.update_attributes(:ordinal => ordinal) if pre_dandan && (ordinal != 0)
    end
    redirect_to :action => :index
  end

  #下移
  def down_index
    min_ordinal = @dandan_class.pluck.min
    dandan = @dandan_class.find params[:id]
    unless dandan.ordinal == min_ordinal
      next_dandan = @dandan_class.where(:ordinal => dandan.ordinal-1).first
      if next_dandan
        next_ordinal = next_dandan.ordinal
        ordinal = dandan.ordinal
        dandan.update_attributes(:ordinal => next_ordinal)
        next_dandan.update_attributes(:ordinal => ordinal)
      end
    end
    redirect_to :action => :index
  end
  
  #删除排序
  def del_index
     dandan = @dandan_class.find params[:id]
     index = dandan.ordinal
 
     
    sql = "update news set ordinal = ordinal-1 where ordinal >#{dandan.ordinal}"
        ActiveRecord::Base.connection.execute(sql)
    dandan.update_attributes(:ordinal => 0)

    
     
     redirect_to :action => :index
  end


  private
  def set_seach_data
    session[:article_type] = params[:article_type] if params[:article_type]
    session[:on_index] = params[:on_index] if params[:on_index]
  end

  def get_class
    case session[:article_type]
      when '校园要闻'
        @dandan_class = News
      when '校园快讯'
        @dandan_class = News
      when '热点专题'
        @dandan_class = Sptitle
    end
  end
end
